package com.wt.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 利用重入锁的condition实现10个线程都初始化完毕之后在同时开始执行
 * @author: wangtao
 * @date:10:00 2019/6/12
 * @email:386427665@qq.com
 */
public class ThreadReentrantLockCondition implements Runnable {

    volatile static int num = 0;

    static ReentrantLock lock = new ReentrantLock(true);
    static Condition condition = lock.newCondition();

    private String name;

    public ThreadReentrantLockCondition(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (num < 9) {
                try {
                    num++;
                    System.out.println("current num = " + num);
                    //必须在获得锁之后才能调用
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                condition.signalAll();
            }
            try {
                System.out.println(name + " get lock");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            new Thread(new ThreadReentrantLockCondition("t" + i)).start();
            System.out.println("insert t" + i);
            Thread.sleep(500);
        }
    }
}
